import { Suspense, lazy, useEffect } from 'react';

import { Spin } from 'antd';
import { observer } from 'mobx-react-lite';

import { useStore } from '@/store';
import { layoutStore } from '@/store/layout';

import { usePermission } from '@/auth';

import Exception403 from '../exception/403';
import styles from './index.module.scss';

const Permission: React.FC<
  React.PropsWithChildren<{
    authority?: RouteData['authority'];
    room?: RouteData['room'];
  }>
> = observer(({ children, authority, room }) => {
  const { check } = usePermission();
  const store = useStore();

  if (Array.isArray(room)) {
    if (!room.includes(store.config['网站标题']?.configValue)) {
      return <Exception403 />;
    }
  }

  if (check(authority)) {
    return children;
  }

  return <Exception403 />;
});

export function lazyLoad(
  url: ArgumentsType<typeof lazy>[0],
  authority: undefined | RouteData['authority'],
  room?: string[]
) {
  const Module = lazy(url);

  return (
    <Permission authority={authority} room={room}>
      <Suspense fallback={<Loadable />}>
        <Module />
      </Suspense>
    </Permission>
  );
}

const Loadable: React.FC = () => {
  // 显示加载动画
  useEffect(() => {
    layoutStore.loading = true;

    return () => {
      layoutStore.loading = false;
    };
  }, []);

  return (
    <div className={styles['loadable']}>
      <Spin size="large" />
    </div>
  );
};

export default Loadable;
